<template>
  <div class="class-list-page">
    <!-- 搜索栏 -->
    <el-card shadow="never" style="margin-bottom: 20px">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="年级">
          <el-select
            v-model="filterForm.grade"
            placeholder="全部年级"
            clearable
            style="width: 150px"
            @change="handleSearch"
          >
            <el-option
              v-for="grade in grades"
              :key="grade"
              :label="grade"
              :value="grade"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="关键词">
          <el-input
            v-model="filterForm.keyword"
            placeholder="班级名称或班主任"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增班级
          </el-button>
          <el-button type="warning" @click="handleSync">
            <el-icon><Refresh /></el-icon>
            同步班级数据
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 班级列表 -->
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span class="card-title">
            <el-icon><School /></el-icon>
            班级列表
          </span>
          <span class="card-extra">共 {{ total }} 个班级</span>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="classList"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="className" label="班级名称" min-width="120">
          <template #default="{ row }">
            <el-link type="primary" @click="handleDetail(row._id)">
              {{ row.className }}
            </el-link>
          </template>
        </el-table-column>

        <el-table-column prop="grade" label="年级" width="100" />

        <el-table-column prop="headTeacher" label="班主任" width="120">
          <template #default="{ row }">
            {{ row.headTeacher || '-' }}
          </template>
        </el-table-column>

        <el-table-column prop="studentCount" label="学生人数" width="100" align="center">
          <template #default="{ row }">
            <el-tag>{{ row.studentCount }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="averageScore" label="班级平均分" width="120" align="center">
          <template #default="{ row }">
            <el-tag
              v-if="row.studentCount > 0"
              :type="getScoreType(row.averageScore)"
            >
              {{ row.averageScore }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <el-table-column prop="description" label="备注" min-width="150">
          <template #default="{ row }">
            {{ row.description || '-' }}
          </template>
        </el-table-column>

        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              :icon="View"
              @click="handleDetail(row._id)"
            >
              详情
            </el-button>
            <el-button
              type="warning"
              size="small"
              :icon="Edit"
              @click="handleEdit(row._id)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              :icon="Delete"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete, View, Plus } from '@element-plus/icons-vue'
import { getClasses, getGrades, deleteClass, syncClasses } from '@/api/class'

const router = useRouter()

// 数据
const loading = ref(false)
const classList = ref([])
const grades = ref([])
const total = ref(0)

// 筛选表单
const filterForm = reactive({
  grade: '',
  keyword: ''
})

// 加载班级列表
const loadClasses = async () => {
  try {
    loading.value = true
    const res = await getClasses(filterForm)
    classList.value = res.data.data
    total.value = res.data.data.length
  } catch (error) {
    ElMessage.error('加载班级列表失败')
  } finally {
    loading.value = false
  }
}

// 加载年级列表
const loadGrades = async () => {
  try {
    const res = await getGrades()
    grades.value = res.data.data
  } catch (error) {
    console.error('加载年级列表失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  loadClasses()
}

// 重置
const handleReset = () => {
  filterForm.grade = ''
  filterForm.keyword = ''
  loadClasses()
}

// 新增
const handleAdd = () => {
  router.push('/classes/add')
}

// 编辑
const handleEdit = (id) => {
  router.push(`/classes/edit/${id}`)
}

// 查看详情
const handleDetail = (id) => {
  router.push(`/classes/detail/${id}`)
}

// 删除
const handleDelete = (row) => {
  if (row.studentCount > 0) {
    ElMessageBox.confirm(
      `${row.className} 班级下还有 ${row.studentCount} 名学生，无法删除。请先将学生转移到其他班级。`,
      '无法删除',
      {
        confirmButtonText: '知道了',
        showCancelButton: false,
        type: 'warning'
      }
    )
    return
  }

  ElMessageBox.confirm(
    `确定要删除 ${row.className} 吗？此操作不可恢复！`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteClass(row._id)
      ElMessage.success('删除成功')
      loadClasses()
    } catch (error) {
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }).catch(() => {})
}

// 同步班级数据
const handleSync = () => {
  ElMessageBox.confirm(
    '这将会自动将学生表中已有的班级信息同步到班级管理表中，是否继续？',
    '同步确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(async () => {
    try {
      loading.value = true
      const res = await syncClasses()
      const { synced, skipped, total } = res.data.data
      
      ElMessageBox.alert(
        `同步完成！<br/>
        <br/>
        总计: ${total} 个班级<br/>
        新增: ${synced} 个班级<br/>
        跳过: ${skipped} 个已存在的班级`,
        '同步结果',
        {
          confirmButtonText: '知道了',
          type: 'success',
          dangerouslyUseHTMLString: true
        }
      )
      
      // 重新加载班级列表
      loadClasses()
      loadGrades()
    } catch (error) {
      ElMessage.error(error.response?.data?.message || '同步失败')
    } finally {
      loading.value = false
    }
  }).catch(() => {})
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

// 获取分数标签类型
const getScoreType = (score) => {
  if (score >= 90) return 'success'
  if (score >= 80) return ''
  if (score >= 70) return 'warning'
  return 'danger'
}

onMounted(() => {
  loadClasses()
  loadGrades()
})
</script>

<style scoped>
.class-list-page {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
}

.card-extra {
  font-size: 14px;
  color: #909399;
}
</style>
